#include "s12d.h"

#include "iot_adc.h"
#include "iot_errno.h"

/* 定义ADC的通道号 */
#define ADC_CHANNEL 6

/**
 * @brief s12d 初始化
 *
 */
void s12d_init(void)
{
    uint8_t ret = 0;

    ret = IoTAdcInit(ADC_CHANNEL);
    if (ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: ADC Init fail\n", __FILE__, __func__, __LINE__);
    }
}

void s12d_deinit(void)
{
    IoTAdcDeinit(ADC_CHANNEL);
}

/**
 * @brief 获取 s12d 电压
 *
 * @return double 电压值
 */
static double s12d_get_voltage(void)
{
    uint32_t data = 0;
    uint8_t ret = IOT_SUCCESS;

    ret = IoTAdcGetVal(ADC_CHANNEL, &data);
    if (ret != IOT_SUCCESS)
    {
        printf("%s, %s, %d: ADC Read Fail\n", __FILE__, __func__, __LINE__);
        return 0.0;
    }

    double voltage = (double)(data * 3300.0 / 1023.0);

    return voltage;
}

/**
 * @brief 获取紫外线等级
 *
 * @return uv_index_e 紫外线等级
 */
uv_index_e s12d_get_uv_index(void)
{
    double data = s12d_get_voltage();
    uv_index_e rusult = 0;

    if (data < 50)
    {
        rusult = UV_INDEX_0;
    }
    else if (data >= 50 && data < 227)
    {
        rusult = UV_INDEX_1;
    }
    else if (data >= 227 && data < 318)
    {
        rusult = UV_INDEX_2;
    }
    else if (data >= 318 && data < 408)
    {
        rusult = UV_INDEX_3;
    }
    else if (data >= 408 && data < 503)
    {
        rusult = UV_INDEX_4;
    }
    else if (data >= 503 && data < 606)
    {
        rusult = UV_INDEX_5;
    }
    else if (data >= 606 && data < 696)
    {
        rusult = UV_INDEX_6;
    }
    else if (data >= 696 && data < 795)
    {
        rusult = UV_INDEX_7;
    }
    else if (data >= 795 && data < 881)
    {
        rusult = UV_INDEX_8;
    }
    else if (data >= 881 && data < 976)
    {
        rusult = UV_INDEX_9;
    }
    else if (data >= 976 && data < 1079)
    {
        rusult = UV_INDEX_10;
    }
    else if (data >= 1079)
    {
        rusult = UV_INDEX_11;
    }

    return rusult;
}
